package com.xdap.init.service.impl;

import com.xdap.api.moudle.formconfig.pojo.XdapFormConfig;
import com.xdap.api.moudle.privateapaas.datamodel.pojo.ModelWithFieldVo;
import com.xdap.common.dao.InitFormDao;
import com.xdap.common.utils.ExcelUtil;
import com.xdap.common.utils.InitDateFormatUtil;
import com.xdap.common.utils.TxtUtil;
import com.xdap.init.dao.ModelDao;
import com.xdap.init.dao.ModelFeildDao;
import com.xdap.init.pojo.po.DataModel;
import com.xdap.init.pojo.po.DataModelField;
import com.xdap.init.service.InitLastingService;
import com.xdap.init.service.JudgeModelService;
import com.xdap.init.utils.CreateJavaFIleUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class InitLastingServiceImpl implements InitLastingService {
    @Autowired
    private InitFormDao initFormDao;
    @Autowired
    private ModelFeildDao modelFeildDao;
    @Autowired
    private ModelDao modelDao;
    @Autowired
    private JudgeModelService judgeModelService;


    /**
     * @auth lishushu
     * @2023/4/21 11:02
     * @desc {根据formId，生成当前页面所有的po对象}
     **/
    @Override
    public String initLasting(String filePath, String formId, String packageName) {
        //
        String result = "";
        XdapFormConfig xdapFormConfig = initFormDao.getXdapFormConfig(formId);
        List<ModelWithFieldVo> modelWithFieldVoList = xdapFormConfig.getModelWithFieldVoList();
        // 先校验模型的字段注释和表单页面上保持一致
        String s = judgeModelService.judgeModelByFormConfig(xdapFormConfig);
        log.info("校验当前模型字段注释和页面上的中文名称保持一致\t：{}", s);

        for (ModelWithFieldVo modelWithFieldVo : modelWithFieldVoList) {
            String modelCode = modelWithFieldVo.getModelCode();
            result += initLastingByTableName(filePath, modelCode, packageName);
        }

        return result;
    }

    /**
     * @auth lishushu
     * @2023/4/21 13:50
     * @desc {根据表名称，直接创建}
     **/
    @Override
    public String initLastingByTableName(String filePath, String modelCode, String packageName) {

        String result = "";

        if (!filePath.contains("\\com\\xdap\\")) {
            filePath = filePath + "\\com\\xdap\\" + packageName;
        }

        // 初始化名称 定义常用到的对象
        String po = TxtUtil.camelize(modelCode);
        String upperPo = po.substring(0, 1).toUpperCase() + po.substring(1);
        DataModel model = modelDao.getModel(modelCode);
        List<DataModelField> fields = modelFeildDao.getFields(modelCode);
        fields.stream().forEach(field -> {
            field.setFieldName(TxtUtil.camelize(field.getFieldCode()));
        });
        String logger = "处理" + modelCode + ":" + model.getModelName();
        String time = InitDateFormatUtil.getCurrentYyyyMmDdHhMiSsCc(); // 获取当前时间


        // 替换po内的参数，实现方法的创建----------------PO---------- TODO 待其他数据处理结束之后再处理这里
        // 添加参数
        VelocityContext contextPo = new VelocityContext();
        contextPo.put("packageName", packageName);
        contextPo.put("className", packageName); // TODO 以后再修改这个地方的代码，保证每次调用是实际的package
        contextPo.put("upperPo", upperPo);
        contextPo.put("po", po);
        contextPo.put("modelCode", modelCode);
        contextPo.put("fields", fields);
        contextPo.put("time", time);
        contextPo.put("log", logger);

        result += CreateJavaFIleUtils.createJava
                (filePath + "\\pojo\\po", upperPo + "Po", "base/po.vm", contextPo);
        // 替换vo的内容参数-----------VO-------------
        // 添加参数
        VelocityContext contextVo = new VelocityContext();
        contextVo.put("className", packageName); // TODO 后续修改成读取实际地址的
        contextVo.put("packageName", packageName);
        contextVo.put("upperPo", upperPo);
        contextVo.put("modelCode", modelCode);
        contextVo.put("po", po);
        contextVo.put("time", time);
        contextVo.put("fields", fields);
        contextVo.put("log", logger);

        result += CreateJavaFIleUtils.createJava
                (filePath + "\\pojo\\vo", upperPo + "Vo", "base/vo.vm", contextVo);

        // ---------------------处理dao层数据
        // 添加参数
        VelocityContext contextDao = new VelocityContext();
        contextDao.put("packageName", packageName);
        contextDao.put("className", packageName); // TODO 后续修改成读取实际地址的
        contextDao.put("upperPo", upperPo);
        contextDao.put("modelCode", modelCode);
        contextDao.put("logger", logger);
        contextDao.put("po", po);
        contextDao.put("time", time);
        result += CreateJavaFIleUtils.createJavaIfNot
                (filePath + "\\dao", upperPo + "Dao", "base/dao.vm", contextDao);


        return result;
    }

    @Override
    public String targetExcel(String filePath) {
        //将Excel导入到模型页面
        List<List<Map<String, Object>>> lists = ExcelUtil.importExcel(filePath, 1, 1, 1);
        //模型新建
        String modelName = filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.lastIndexOf("."));
        modelDao.saveModel(modelName);
        log.info("modelName = " + modelName);

        DataModelField field = new DataModelField();
        //字段新建
        //sheet
        for (List<Map<String, Object>> list : lists) {
            //单个表格
            for (Map<String, Object> stringObjectMap : list) {
                Set<Map.Entry<String, Object>> entrySet = stringObjectMap.entrySet();
                for (Map.Entry<String, Object> entry : entrySet) {
                    String firstRowSheet = entry.getKey();
                    String value = (String) entry.getValue();
                    switch (firstRowSheet) {
                        case "col1":
                            field.setFieldCode(value);
                            break;
                        case "col2":
                            field.setFieldName(value);
                            break;
                        case "col3":
                            field.setFieldType(value);
                            break;
                        case "col4":
                            field.setFieldStatus(value);
                            break;
                        case "col5":
                            field.setModelCode(value);
                            break;
                        case "col6":
                            field.setModelId(value);
                            break;
                        case "col7":
                            field.setMaxLength(value);
                            break;
                        case "col8":
                            field.setFieldModify(value);
                            break;
                        case "col9":
                            field.setGenerateType(value);
                            break;
                        case "col10":
                            field.setFieldTypeDisplay(value);
                            break;
                        case "col11":
                            field.setFieldComment(value);
                            break;
                        default:
                            return "识别列失败";
                    }
                }
            }
        }
        modelFeildDao.insertField(field);
        log.info("field=" + field);
        return "导入成功";
    }
}